package session

import (
	"net/http"

	"gitee.com/mkwchecking/sr-core/yerr"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

const (
	_sessionCtxKey = "yy-sidecar-session"
	_sessionIdKey  = "yy-sidecar-session-id"
)

func Middleware(cfg *SessionManager) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		ctx.Set(_sessionCtxKey, cfg)
		ctx.Next()
	}
}

/*
func MiddlewareE(ctx context.Context, cfg *SessionConfig) (gin.HandlerFunc, error) {

		sessManager, err := NewSessionManager(ctx, cfg)
		if err != nil {
			return nil, err
		}

		return func(ctx *gin.Context) {
			ctx.Set(_sessionCtxKey, sessManager)

			ctx.Next()
		}, nil
	}
*/
func GetManagerMW(ctx *gin.Context) (*SessionManager, error) {
	if sess, ok := ctx.Get(_sessionCtxKey); ok {
		if sm, ok := sess.(*SessionManager); ok {
			return sm, nil
		}
	}

	return nil, yerr.ErrBizPluginNotFound.Error("session")
}

func GetStore(ctx *gin.Context) (sessions.Session, error) {
	sess := sessions.Default(ctx)
	return sess, nil
}

func GetSessionId(ctx *gin.Context) (string, error) {
	sessId := ctx.GetString(_sessionIdKey)
	if sessId != "" {
		return sessId, nil
	}

	sess, err := GetStore(ctx)
	if err != nil {
		return "", err
	}

	sessId = sess.ID()
	if sessId != "" {
		ctx.Set(_sessionIdKey, sessId)
	}
	return sessId, nil
}

func (s *SessionManager) Auth(ctx *gin.Context) {

	sessId, err := s.GetSessionId(ctx.Request)
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusForbidden, gin.H{
			"msg":  "Auth failed",
			"code": http.StatusForbidden,
		})

		return
	} else {
		ctx.Set(_sessionCtxKey, s)
		ctx.Set(_sessionIdKey, sessId)
	}
	ctx.Next()

}
